﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using SuperSocket;
using SuperSocket.Channel;

namespace Lawn.AppServer
{
    public static class ServerExtensions
    {


        public static IServiceCollection AddCommand(this IServiceCollection service)
        {

            service.AddTransient<IMessageFactory, DefaultMessageFactory>();
            service.AddOptions<OptionCommandType>();
            service.AddTransient<NoSupportProtoMessageHandler>();
            service.AddTransient<SubMessageHandler>();
            service.AddTransient<PubMessageHandler>();
            return service;
        }
        public static ISuperSocketHostBuilder UseSocket(this IHostBuilder builder)
        {
            return builder.AsSuperSocketHostBuilder<MessagePackageInfo, MessagePipelineFilter>()
                .UseSession<MessageAppSesssion>()

                .UsePackageHandler(async (session, info) =>
                {
                    using (IServiceScope scope = session.Server.ServiceProvider.CreateScope())
                    {
                        var cmd = scope.ServiceProvider.GetRequiredService<IMessageAsyncCommand>();
                        await cmd.PackageHandler(session, info);
                    }
                });
            // },(async (session, exception) =>
            // {
            //
            //     Log.Error(exception,"ex");
            //    await session.CloseAsync(CloseReason.InternalError);
            //     return true;
            // } ));
        }
    }
}